package com.demo.queue;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class MessageSender {
	
	private static final int SEND_NUM = 5;
	
	public static final String DESTINATION = "mq.queue";
	
	public static void sendMessage(Session session,MessageProducer producer) throws JMSException{
		//for (int i = 0; i < SEND_NUM; i++) {
			String message = "发送消息";
			TextMessage textMessage = session.createTextMessage(message);
			producer.send(textMessage);
		//}
	}
	
	public static void run() throws JMSException{
		Connection connection = null;
		Session session = null;
		try {
			// 1.初始化connection工厂  
			ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
					ActiveMQConnection.DEFAULT_PASSWORD, ActiveMQConnection.DEFAULT_BROKER_URL);
			// 2.创建Connection  
			connection = factory.createConnection();
			// 3.打开连接  
			connection.start();
			// 4.创建session  
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			// 5.创建消息目的地  
			Destination destination = session.createTopic(DESTINATION);
			//6.创建生产者
			MessageProducer producer = session.createProducer(destination);
			//7.配置消息持久化
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			//8.发送消息
			sendMessage(session, producer);
			//9.事务提交
			session.commit();
		} catch (Exception e) {
			throw e;
		}finally {
			if(session!=null){
				session.close();
			}
			if(connection != null){
				connection.close();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		MessageSender.run();
	}
}
